<template>
  <div ref="dom" class="charts chart-bar"></div>
</template>

<script>
import echarts from 'echarts'
import tdTheme from './theme.json'
import { on, off } from '@/libs/tools'
echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    barObj: Object,
    text: String,
    subtext: String
  },
  watch: {
    barObj: {
　　　　handler (newValue, oldValue) {
          this.barObj = newValue
          this.renderData()
　　　　},
　　　　deep: true
　　}
  },
  data () {
    return {
      dom: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    renderData () {
      this.$nextTick(() => {
        let option = {
          title: {
            text: this.text,
            subtext: this.subtext
          },
          grid: {
              left: '1%',
              right: '1%',
              bottom: '1%',
              containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: this.barObj.xDatas,
            axisTick: {
              alignWithLabel: true
            }
          },
          yAxis: {
            name: '用电((kwh)',
            type: 'value'
          },
          series: [{
            data: this.barObj.yDatas,
            type: 'bar',
            barWidth: '60%'
          }]
        }
        this.dom = echarts.init(this.$refs.dom, 'tdTheme')
        this.dom.setOption(option)
        on(window, 'resize', this.resize)
      })
    }
  },
  mounted () {
    this.$nextTick(() => {
      let option = {
        title: {
          text: this.text,
          subtext: this.subtext
        },
        grid: {
            left: '1%',
            right: '1%',
            bottom: '1%',
            containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.barObj.xDatas,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.barObj.yDatas,
          type: 'bar',
          barWidth: '60%'
        }]
      }
      this.dom = echarts.init(this.$refs.dom, 'tdTheme')
      this.dom.setOption(option)
      on(window, 'resize', this.resize)
    })
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
